package com.javastar.modules.security.handler;

import cn.hutool.core.date.DateUtil;
import com.javastar.common.enums.TokenEnum;
import com.javastar.common.result.Result;
import com.javastar.common.utils.JwtUtil;
import com.javastar.common.utils.ResponseUtil;
import com.javastar.common.utils.UserHolderUtil;
import com.javastar.modules.security.bean.SysUserDetails;
import com.javastar.modules.security.vo.SysUserVO;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;

/**
 * 认证成功处理器
 *
 * @author zxx
 * @date 2023/7/25
 */
@Component
public class SysAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
    /**
     * 用户名密码认证成功后调用，生成token并返回
     * @param request the request which caused the successful authentication
     * @param response the response
     * @param authentication the <tt>Authentication</tt> object which was created during
     * the authentication process.
     * @throws IOException
     * @throws ServletException
     */
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        SysUserDetails sysUserDetails = UserHolderUtil.getUserDetailsFromAuthentication(authentication);
        String adminToken = JwtUtil.generateToken(sysUserDetails.getId(), TokenEnum.ADMIN_TOKEN);
        SecurityContextHolder.getContext().setAuthentication(authentication);
        SysUserVO sysUserVO = new SysUserVO();
        sysUserVO.setUserId(sysUserDetails.getId());
        sysUserVO.setRealName(sysUserDetails.getRealName());
        sysUserVO.setToken(adminToken);
        sysUserVO.setExpireDate(DateUtil.offsetDay(new Date(), 1));
        ResponseUtil.write(response, new Result().ok(sysUserVO));
    }
}
